package top.chukongxiang.project.base.service.sys.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import top.chukongxiang.project.base.mapper.sys.RoleMapper;
import top.chukongxiang.project.base.model.entity.sys.Role;
import top.chukongxiang.project.base.model.entity.user.RoleUser;
import top.chukongxiang.project.base.service.sys.RoleService;
import top.chukongxiang.project.base.service.user.RoleUserService;

/**
 * 角色Service实现
 * @author 楚孔响
 * @version 1.0
 * @date 2022/2/21 16:32
 */
@Service
@Slf4j
public class RoleServiceImpl extends ServiceImpl<RoleMapper, Role> implements RoleService {

    @Autowired
    RoleUserService roleUserService;

    @Override
    public void changeDefaultRole(Long roleId) {
        update(Wrappers.<Role>lambdaUpdate().set(Role::getIsDefault, false).ne(Role::getId, roleId));
        update(Wrappers.<Role>lambdaUpdate().set(Role::getIsDefault, true).eq(Role::getId, roleId));
    }

    @Override
    public Role defaultRole() {
        return getOne(Wrappers.<Role>lambdaQuery().eq(Role::getIsDefault, true));
    }

    @Override
    public boolean setUserRole(String userId, Long roleId) {
        roleUserService.remove(Wrappers.<RoleUser>lambdaQuery().eq(RoleUser::getUserId, userId));
        RoleUser roleUser = new RoleUser(null, roleId, userId);
        return roleUserService.save(roleUser);
    }
}
